package com.zjshell.pricing.price.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjshell.pricing.common.entity.FebsConstant;
import com.zjshell.pricing.common.entity.QueryRequest;
import com.zjshell.pricing.common.utils.SortUtil;
import com.zjshell.pricing.price.entity.OilPrice;
import com.zjshell.pricing.price.mapper.OilPriceMapper;
import com.zjshell.pricing.price.service.IOilPriceService;
import com.zjshell.pricing.site.entity.ShellSite;


@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OilPriceServiceImpl extends ServiceImpl<OilPriceMapper, OilPrice> implements IOilPriceService{
	
	@Autowired
	private OilPriceMapper oilPriceMapper;
	
	@Override
	public OilPrice findById(OilPrice oilPrice) {
		return oilPriceMapper.findById(oilPrice);
	}

	@Override
	public List<OilPrice> findBySiteId(OilPrice oilPrice) {
		return oilPriceMapper.findBySiteId(oilPrice);
	}

	@Override
	public void deleteOilPrices(String[] ids) {
		delete(Arrays.asList(ids));
	}

	@Override
	public void updateOilPrice(OilPrice oilPrice) {
		this.baseMapper.updateById(oilPrice);
	}

	private void delete(List<String> ids) {
        removeByIds(ids);
        LambdaQueryWrapper<OilPrice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(OilPrice::getId, ids);
        List<OilPrice> oilPrices = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(oilPrices)) {
            List<String> dseptIdList = new ArrayList<>();
            oilPrices.forEach(d -> dseptIdList.add(String.valueOf(d.getId())));
            this.delete(dseptIdList);
        }
    }

	@Override
	public void createOilPrice(OilPrice oilPrice) {
		this.baseMapper.insert(oilPrice);
	}

	@Override
	public IPage<OilPrice> findOilPriceDetail(OilPrice oilPrice, QueryRequest request) {
		Page<OilPrice> page = new Page<>(request.getPageNum(), request.getPageSize());
        SortUtil.handlePageSort(request, page, "id", FebsConstant.ORDER_DESC, false);
        return this.baseMapper.findOilPricePage(page, oilPrice);
	}
}
